package com.moody.init;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.moody.hibernate.dao.RightInfoDAO;
import com.moody.hibernate.dao.RoleInfoDAO;
import com.moody.hibernate.dao.RoleRightDAO;
import com.moody.hibernate.domain.RightInfo;
import com.moody.hibernate.domain.RoleInfo;
import com.moody.hibernate.domain.RoleRight;

/*
 * 获得所有的角色和url的对应
 */


public class RoleRightInit {
	private static final Logger log = LoggerFactory.getLogger(RoleRightInit.class);
	private static RoleRightInit instance = null;
	static WebApplicationContext web = ContextLoader.getCurrentWebApplicationContext();
	static ServletContext context = web.getServletContext();  
	static WebApplicationContext ctx  = WebApplicationContextUtils.getWebApplicationContext(context);
	private static RightInfoDAO rightInfoDAO = RightInfoDAO.getFromApplicationContext(ctx);
	private static RoleRightDAO roleRightDAO = RoleRightDAO.getFromApplicationContext(ctx);
	private static RoleInfoDAO roleInfoDAO = RoleInfoDAO.getFromApplicationContext(ctx);
	private static Map<String,Map<String,String>> roleURLMap = new HashMap<String,Map<String,String>>();
	
	private RoleRightInit() {
	}
	
	public static RoleRightInit getInstance(){
		if(instance == null){
			instance = new RoleRightInit();
		}
		return instance;
	}
	
	@SuppressWarnings("unchecked")
	//key 为权限，value为可以访问的链接
	public Map<String,Map<String,String>> getRightMap(){
		List<RoleInfo> roleInfo = roleInfoDAO.findAll();

		if(roleURLMap.size() == 0 ){
			for(RoleInfo role : roleInfo){
				List<RoleRight> roleRightList = roleRightDAO.findByProperty("id.roleId", role.getRoleId());
				String accessURL = "";
				String deniedURL = "";
				for(RoleRight rr : roleRightList){
					RightInfo rightInfo = rightInfoDAO.findById(rr.getId().getRightId());
					
					if(rightInfo!=null && !("").equals(rightInfo.getAvailableUrl())){
						accessURL += rightInfo.getAvailableUrl() +";";
					}
					
					if(rightInfo!=null && !("").equals(rightInfo.getDeniedUrl())){
						deniedURL += rightInfo.getDeniedUrl() + ";";
					}
				}
				
				Map urlMap = new HashMap<String,String>(); 
				urlMap.put("accessURL", accessURL);
				urlMap.put("deniedURL", deniedURL);
				
				roleURLMap.put(role.getRoleId(), urlMap);
			}
			//log.info("roleURL: "+roleURLMap);
			return roleURLMap;
		}else{
			//log.info("roleURL: "+roleURLMap);
			return roleURLMap;
		}
	}
}
